package com.how2java;

import com.how2java.pojo.Category;
import com.how2java.pojo.Order;
import com.how2java.pojo.OrderItem;
import com.how2java.pojo.Product;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestMybatis {

    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
//模糊查询使用
        System.out.println("单表复杂查询：模糊查询");
        List<Category> cs = session.selectList("listCategoryByName", "cat");
        for (Category c : cs) {
            System.out.println(c.getName());
        }

//因为是多个参数，而selectList方法又只接受一个参数对象，所以需要把多个参数放在Map里，然后把这个Map对象作为参数传递进去
        System.out.println("单表复杂查询：多参数传递");
        Map<String, Object> params = new HashMap<>();
        params.put("id", 3);
        params.put("name", "cat");
        cs = session.selectList("listCategoryByIdAndName", params);

//
//        Category c=new Category();
//        c.setId(3);
//        c.setName("cat");
//        cs = session.selectList("listCategoryByIdAndName2", params);


        //一对多查询调用
        System.out.println("一对多查询");
        cs = session.selectList("listCategory2");
        for (Category c : cs) {
            System.out.println(c);
            List<Product> ps = c.getProducts();
            for (Product p : ps) {
                System.out.println("\t" + p);
            }
        }
        //多对一查询
        System.out.println("多对一查询");
        List<Product> ps = session.selectList("listProduct");
        for (Product p : ps) {
            System.out.println(p + " 对应的分类是 \t " + p.getCategory());
        }


        //多对多查询
        System.out.println("多对多查询");
        List<Order> os = session.selectList("listOrder");
        for (Order o : os) {
            System.out.println(o.getCode());
            List<OrderItem> ois = o.getOrderItems();
            for (OrderItem oi : ois) {
                System.out.format("\t%s\t%f\t%d%n", oi.getProduct().getName(), oi.getProduct().getPrice(), oi.getNumber());
            }
        }

        session.commit();
        session.close();

    }

}